import axios from "axios";
import qs from "qs";
import merge from "lodash/merge";
import api from "./api.js";
import auth from "@/storage/auth.js";
//默认传递参数
let defaultParams = {};
let client = axios.create({
  baseURL: process.env.VUE_APP_URL,
  transformRequest: [
    function (data, headers) {
      if (
        headers["Content-Type"]?.toLowerCase().replaceAll(" ", "") ===
        "application/json;charset=utf-8"
      ) {
        merge(defaultParams, data);
        return JSON.stringify(defaultParams);
      } else if (
        headers["Content-Type"]?.toLowerCase().replaceAll(" ", "") ===
        "application/x-www-form-urlencoded"
      ) {
        merge(defaultParams, data);
        return qs.stringify(defaultParams);
      } else if (
        headers["Content-Type"]?.toLowerCase().replaceAll(" ", "") ===
        "multipart/form-data;charset=UTF-8"
      ) {
        return data;
      }
      return data;
    },
  ],
});
for (let prop in api) {
  let p = {};
  merge(p, api[prop]);
  client[prop] = function (data) {
    let headers = {
      token: auth.getToken(),
    };
    merge(headers, {
      "Content-Type": "application/x-www-form-urlencoded",
    });
    merge(headers, p.header);
    if (data instanceof FormData) {
      merge(headers, {
        "Content-Type": "multipart/form-data",
      });
      return client.post(p.url, data, {
        headers: headers,
      });
    }
    let params = {};
    merge(params, p.default);
    merge(params, data);
    console.log("请求接口", headers);
    // if (p.method.toLowerCase() === "post") {
    // } else if (p.method.toLowerCase() === "get") {
    // }
    return client.request({
      method: p.method,
      url: p.url,
      data: params,
      headers: headers,
    });
  };
}
client.auth = auth;
export default client;
